<?php
/**
 * File containing the BRail_Ldap_Adapter class.
 * @package BRail_Ldap
 */

/**
 * @package BRail_Ldap
 */
class BRail_Ldap_Adapter
{
    const BASE_DN = 'OU=Unit placeholder,DC=msnet,DC=railb,DC=be';

    /**
     * @var resource $_ldapLink
     */
    private $_ldapLink = null;

    /**
     * @param array $config
     * @throws BRail_Ldap_Exception
     */
    public function __construct(array $config)
    {
        if (!(isset($config['username']) && !empty($config['username']) &&
              isset($config['password']) && !empty($config['password']) &&
              isset($config['host'])     && !empty($config['host'])     &&
              isset($config['port'])     && !empty($config['port']))) {
            throw new BRail_Ldap_Exception(
                'Config array passed to '.__METHOD__.' misses some parameters.'
            );
        }

        // Always return a resource as it does not connect but initializes parameters
        $this->_ldapLink = ldap_connect($config['host'], $config['port']);

        ldap_set_option($this->_ldapLink, LDAP_OPT_PROTOCOL_VERSION, 3);
        ldap_set_option($this->_ldapLink, LDAP_OPT_REFERRALS, 0);

        // Connection is only made here
        if (!@ldap_bind($this->_ldapLink, 'MSNET\\' . $config['username'], $config['password'])) {
            throw new BRail_Ldap_Exception('LDAP Error : '. ldap_error($this->_ldapLink));
        }
    }

    /**
     * Close LDAP connection
     */
    public function __destruct()
    {
        if (is_resource($this->_ldapLink)) {
            ldap_close($this->_ldapLink);
        }
    }

    /**
     * @param string $filter
     * @param array $fields
     * @return array
     */
    public function execute($filter, $fields)
    {
        return ldap_get_entries(
            $this->_ldapLink,
            ldap_search($this->_ldapLink, self::BASE_DN, $filter, $fields)
        );
    }
}